<?php

namespace app\admin\service;

use app\common\model\trCar;
use app\common\model\trCarList;
use app\common\model\trCarType;
use app\common\model\trOutletsCar;
use app\common\util\ErrorCode;
use think\Db;

/**
 * Class OutletCarService
 * @package app\admin\service
 * 网点车服务类
 */
class OutletCarService extends BaseService
{
    protected $field = [
        "outlet_id" => self::FIELD_REQUIRE, "car_id" => self::FIELD_REQUIRE, "price" => 0,
        "week_price" => self::FIELD_REQUIRE, 'special_price' => '', "stock" => 0
    ]; //填入数据库需要存储的表字段

    // 获取网点的车列表
    public function getList(){
        if(empty($this->params["outletId"])){
            return ErrorCode::code("params_not_exist", "outletId");
        }
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;

        $db = trOutletsCar::alias("oc")->with(["plateNumber" => function($query){
            $query->field("id,attr_id");
        }])
            ->leftJoin(trCar::getTable(). " c", "c.id=oc.car_id")
            ->leftJoin(trCarType::getTable(). " ct", "ct.id=c.car_type")
            ->field("oc.*,c.id as carId,c.name,ct.id as carTypeId")
            ->where(["oc.outlet_id" => $this->params["outletId"]]);
        if(!empty($this->params["searchValue"])){
            $db->where([["c.name", "like", $this->params["searchValue"]]]);
        }
        $data = $db->paginate(["list_rows" => $pageSize, "page" => $page]);
        $this->returnData["data"] = $this->convertPageData($data);
        foreach ($this->returnData["data"]["list"] as &$item){
            $item["weekPrice"] = explode(",", $item["weekPrice"]);
            $item["specialPrice"] = @json_decode($item["specialPrice"], true);
            if(!empty($item["plateNumber"])){
                $item["plateNumber"] = array_column($item["plateNumber"], "id");
            }
        }
        unset($item);
        return $this->returnData;
    }

    public function toAdd(){
        $data = $this->extractData([
            "create_time" => time(), "update_time" => time()
        ]);
        if(trOutletsCar::where(["car_id" => $data["car_id"], "outlet_id" => $data['outlet_id']])->count()){
            return ErrorCode::code("customized", "数据重复，请更换车辆");
        }
        $data["over_stock"] = $data["stock"];
        $model = trOutletsCar::create($data);
        if(!$model->id){
            $this->returnData = ErrorCode::code("customized", "添加失败");
        }else{
            if(!empty($this->params["plateNumber"])){
                $stock = 0;
                $plateNumber = explode(",", $this->params["plateNumber"]);
                foreach ($plateNumber as $id){
                    trCarList::where("id", $id)->update(["type" => 5, "attr_id" => $model->id]);
                    $stock++;
                }
                trOutletsCar::where("id", $model->id)->update(["stock" => $stock, "over_stock" => $stock]);
            }
            $this->returnData["msg"] = "添加成功";
        }
        return $this->returnData;
    }

    public function toEdit(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $database = trOutletsCar::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $data = $this->extractData(["update_time" => time()]);
        if(trOutletsCar::where(["car_id" => $data["car_id"], "outlet_id" => $data['outlet_id']])->where("id", "<>", $this->params["id"])->count()){
            return ErrorCode::code("customized", "数据重复，请更换车辆");
        }
        Db::startTrans();
        try {
            $dataId = trCarList::where(["attr_id" => $this->params["id"], "type" => 5])->column("id");
            if (!empty($this->params["plateNumber"])) {
                $data["stock"] = 0;
                $plateNumber = explode(",", $this->params["plateNumber"]);
                foreach ($plateNumber as $id) {
                    trCarList::where("id", $id)->update(["type" => 5, "attr_id" => $this->params["id"]]);
                    $data["stock"]++;
                }
                $diff = array_diff($dataId, $plateNumber);
                if (!empty($diff)) {
                    trCarList::where("id", "in", $diff)->update(["type" => null, "attr_id" => 0]);
                }
            }
            $database->over_stock = $database->over_stock > 0 ? $database->over_stock : 0;
            $stock = $data["stock"] - $database->stock;
            $data["over_stock"] = ($database->over_stock + $stock) > 0 ? $database->over_stock + $stock : 0;
            $database->data($data);
            $database->save();
        }catch (\Exception $e){
            Db::rollback();
            return ErrorCode::code("try_error", $e->getMessage());
        }
        Db::commit();
        $this->returnData["msg"] = "更新成功";
        return $this->returnData;
    }

    public function toUpdateStatus(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        /** @var trOutletsCar $database */
        $database = trOutletsCar::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $database->status = $database->status === 1 ? 2 : 1;
        $database->save();
        $this->returnData["msg"] = "更新成功";
        return $this->returnData;
    }

    public function toDel(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $database = trOutletsCar::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $database->delete();
        $this->returnData["msg"] = "删除成功";
        return $this->returnData;
    }
}